package com.economy.swefunds;

import java.util.ArrayList;
import java.util.Iterator;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;

public class PortfolioList {
	// Singleton
	private static PortfolioList instance = null;
	
	private ArrayList<PortfolioListener> Listeners;

	private DBHelper dbHelper;
	private SQLiteDatabase db;
    private static final String PORTFOLIO_TABLE_NAME = "portfolio";

    protected PortfolioList(Context context) {
		dbHelper = new DBHelper(context, PORTFOLIO_TABLE_NAME, "id TEXT, name TEXT");
		db = dbHelper.getWritableDatabase();

	    Listeners = new ArrayList<PortfolioListener>();
	}

	public static PortfolioList getInstance(Context context) {
		if(instance == null) {
			instance = new PortfolioList(context);
		}
		return instance;
	}
	
	public void addFund(String name, String id) {
		ContentValues values = new ContentValues();
		values.put("id", id);
		values.put("name", name);
		db.insert(PORTFOLIO_TABLE_NAME, null, values);
		updateObservers();
	}
	
	public void removeFund(String id) {
		db.delete(PORTFOLIO_TABLE_NAME, "id=?", new String[] {id});
		updateObservers();
	}
	
	public void removeFundByName(String name) {
		db.delete(PORTFOLIO_TABLE_NAME, "name=?", new String[] {name});
		updateObservers();
	}
	
	public boolean isEmpty() {
		if (DatabaseUtils.queryNumEntries(db, PORTFOLIO_TABLE_NAME) == 0) {
			return true;
		}
		return false;
	}
	
	public ArrayList<String> getNames() {
		ArrayList<String> names = new ArrayList<String>();
		Cursor crsr = db.rawQuery("SELECT * FROM " + PORTFOLIO_TABLE_NAME + ";", null);
		crsr.moveToFirst();
		for(int i=0; i < crsr.getCount(); i++) {
			names.add(new String(crsr.getString(1)));
			crsr.moveToNext();
		}
		crsr.close();
		return names;
	}
	
	public ArrayList<String> getIds() {
		ArrayList<String> ids = new ArrayList<String>();
		Cursor crsr = db.rawQuery("SELECT * FROM " + PORTFOLIO_TABLE_NAME + ";", null);
		crsr.moveToFirst();
		for(int i=0; i < crsr.getCount(); i++) {
			ids.add(new String(crsr.getString(0)));
			crsr.moveToNext();
		}
		crsr.close();
		return ids;
	}
	
	public void updateObservers() {
		Iterator<PortfolioListener> i = Listeners.iterator();
		while (i.hasNext()) {
			PortfolioListener listener = (PortfolioListener)i.next();
			listener.onPortfolioChanged();
		}
	}
	
	public void addObserver(PortfolioListener listener) {
		Listeners.add(listener);
	}
	
	public void removeObserver(PortfolioListener listener) {
		Listeners.remove(listener);
	}
}
